﻿using System.Linq;

using UnityEngine;
using UnityEngine.UI;
using UnityEditor;

/// <summary>
/// Inspector class used to edit UISpriteAnimations.
/// </summary>

[CustomEditor(typeof(UGUISpriteAnimation))]
public class UGUISpriteAnimationInspector : Editor
{
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        GUILayout.Space(3f);
        UGUIEditorTools.SetLabelWidth(80f);
        serializedObject.Update();

        UGUIEditorTools.DrawProperty("Framerate", serializedObject, "mFPS");
        UGUIEditorTools.DrawProperty("Indexes", serializedObject, "mIndexes");
        UGUIEditorTools.DrawProperty("Loop", serializedObject, "mLoop");
        UGUIEditorTools.DrawProperty("Pixel Snap", serializedObject, "mSnap");

        if (GUILayout.Button("Import All Sprites"))
        {
            UGUISpriteAnimation anim = serializedObject.targetObject as UGUISpriteAnimation;

            if (anim != null)
            {
                Image image = anim.GetComponent<Image>();

                if (image != null && image.sprite != null)
                {
                    string assetPath = AssetDatabase.GetAssetPath(image.sprite);
                    var assets = AssetDatabase.LoadAllAssetsAtPath(assetPath).OfType<Sprite>();

                    anim.SetSprites(assets);
                }
            }
        }

        UGUIEditorTools.DrawProperty("Sprites", serializedObject, "sprites");

        serializedObject.ApplyModifiedProperties();
    }

    public static void DrawListProperty(SerializedProperty listProperty)
    {
        if (!listProperty.isArray)
        {
            GUILayout.BeginArea(new Rect(0, 0, 80, 20));
            GUILayout.Label(string.Format("(property '' is not a list)", listProperty.name));
            GUILayout.EndArea();
        }

        EditorGUILayout.PropertyField(listProperty);
        EditorGUI.indentLevel += 1;
        if (listProperty.isExpanded)
        {
            for (int i = 0; i < listProperty.arraySize; i++)
            {
                if(GUILayout.Button("-"))
                {
                    listProperty.DeleteArrayElementAtIndex(i--);
                    continue;
                }

                EditorGUILayout.PropertyField(listProperty.GetArrayElementAtIndex(i), new GUIContent("#" + i));
            }
        }
        EditorGUI.indentLevel -= 1;
    }
}
